<template>
    <div class="container">
        <div class="header">
            <select v-model="selectedTable" @change="fetchData" class="select-table">
                <option value="user_info">用户信息</option>
                <option value="admin_info">管理员信息</option>
            </select>
            <div class="search-filters">
                <input
                    type="text"
                    v-model="searchFilters.id"
                    placeholder="搜索 ID"
                    class="search-input"
                />
                <input
                    type="text"
                    v-model="searchFilters.nickname"
                    placeholder="搜索昵称"
                    class="search-input"
                />
                <input
                    type="text"
                    v-model="searchFilters.company"
                    placeholder="搜索公司"
                    class="search-input"
                />
                <input
                    type="text"
                    v-model="searchFilters.email"
                    placeholder="搜索电子邮件"
                    class="search-input"
                />
                <input
                    type="text"
                    v-model="searchFilters.phone"
                    placeholder="搜索电话号码"
                    class="search-input"
                />
                <button @click="applyFilters" class="search-button">搜索</button>
            </div>
            <button @click="deleteSelected" :disabled="!selectedRows.length" class="delete-button">删除</button>
        </div>

        <table class="data-table">
            <thead>
                <tr>
                    <th><input type="checkbox" @change="toggleSelectAll" :checked="isAllSelected" /></th>
                    <th>ID</th>
                    <th>昵称</th>
                    <th>公司</th>
                    <th>部门</th>
                    <th>职位</th>
                    <th>电子邮件</th>
                    <th>电话号码</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="item in paginatedData" :key="item.info_id">
                    <td><input type="checkbox" :value="item.admin_id || item.user_id" v-model="selectedRows" /></td>
                    <td>{{ item.info_id || item.admin_id || item.user_id }}</td>
                    <td @dblclick="startEdit(item, 'nickname')">
                        <span v-if="editingItem !== item || editingField !== 'nickname'">{{ item.nickname }}</span>
                        <input v-else type="text" v-model="newValue" @blur="saveEdit" @keyup.enter="saveEdit" />
                    </td>
                    <td @dblclick="startEdit(item, 'company')">
                        <span v-if="editingItem !== item || editingField !== 'company'">{{ item.company }}</span>
                        <input v-else type="text" v-model="newValue" @blur="saveEdit" @keyup.enter="saveEdit" />
                    </td>
                    <td @dblclick="startEdit(item, 'department')">
                        <span v-if="editingItem !== item || editingField !== 'department'">{{ item.department }}</span>
                        <input v-else type="text" v-model="newValue" @blur="saveEdit" @keyup.enter="saveEdit" />
                    </td>
                    <td @dblclick="startEdit(item, 'position')">
                        <span v-if="editingItem !== item || editingField !== 'position'">{{ item.position }}</span>
                        <input v-else type="text" v-model="newValue" @blur="saveEdit" @keyup.enter="saveEdit" />
                    </td>
                    <td @dblclick="startEdit(item, 'email')">
                        <span v-if="editingItem !== item || editingField !== 'email'">{{ item.email }}</span>
                        <input v-else type="text" v-model="newValue" @blur="saveEdit" @keyup.enter="saveEdit" />
                    </td>
                    <td @dblclick="startEdit(item, 'phone')">
                        <span v-if="editingItem !== item || editingField !== 'phone'">{{ item.phone }}</span>
                        <input v-else type="text" v-model="newValue" @blur="saveEdit" @keyup.enter="saveEdit" />
                    </td>
                </tr>
            </tbody>
        </table>

        <div class="pagination">
            <button @click="prevPage" :disabled="currentPage === 1" class="pagination-button">上一页</button>
            <span>第 {{ currentPage }} 页 共 {{ totalItems }} 条</span>
            <button @click="nextPage" :disabled="currentPage === totalPages" class="pagination-button">下一页</button>
        </div>

        <confirmation-dialog
            v-if="showConfirmationDialog"
            @confirm="confirmDelete"
            @cancel="cancelDelete"
        />
    </div>
</template>

<script>
import ConfirmationDialog from '../components/ConfirmationDialog.vue'; // 确认对话框组件

export default {
    components: {
        ConfirmationDialog,
    },
    data() {
        return {
            selectedTable: 'user_info', // 默认选择用户信息
            data: [], // 存储用户或管理员信息数据
            selectedRows: [], // 存储选中的行
            currentPage: 1,
            itemsPerPage: 10,
            showConfirmationDialog: false,
            editingItem: null, // 当前正在编辑的项
            editingField: null, // 当前正在编辑的字段
            newValue: '', // 新值
            searchFilters: { // 新增搜索框的绑定数据
                id: '',
                nickname: '',
                company: '',
                email: '',
                phone: '',
            },
            totalItems: 0, // 添加总条目数
        };
    },
    computed: {
        paginatedData() {
            const start = (this.currentPage - 1) * this.itemsPerPage;
            return this.data.slice(start, start + this.itemsPerPage); // 直接使用原始数据
        },
        totalPages() {
            return Math.ceil(this.totalItems / this.itemsPerPage);
        },
        isAllSelected() {
            return this.selectedRows.length === this.data.length;
        },
    },
    methods: {
        fetchData() {
            const endpoint = this.selectedTable === 'user_info' ? 'http://localhost:3000/api/user_info' : 'http://localhost:3000/api/admin_info';
            fetch(endpoint)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    this.data = data; // 确保将数据赋值给 this.data
                    this.totalItems = data.length; // 更新总条目数
                    this.selectedRows = []; // 清空选中的行
                })
                .catch(error => {
                    console.error('获取数据失败:', error);
                });
        },
        applyFilters() {
            const endpoint = this.selectedTable === 'user_info' ? 'http://localhost:3000/api/user_info' : 'http://localhost:3000/api/admin_info';
            const params = new URLSearchParams();
            if (this.searchFilters.id) params.append('id', this.searchFilters.id);
            if (this.searchFilters.nickname) params.append('nickname', this.searchFilters.nickname);
            if (this.searchFilters.company) params.append('company', this.searchFilters.company);
            if (this.searchFilters.email) params.append('email', this.searchFilters.email);
            if (this.searchFilters.phone) params.append('phone', this.searchFilters.phone);

            fetch(`${endpoint}?${params.toString()}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    this.data = data; // 更新数据
                    this.totalItems = data.length; // 更新总条目数
                    this.selectedRows = []; // 清空选中的行
                    this.currentPage = 1; // 重置到第一页
                })
                .catch(error => {
                    console.error('获取数据失败:', error);
                });
        },
        toggleSelectAll(event) {
            if (event.target.checked) {
                this.selectedRows = this.data.map(item => item.admin_id || item.user_id); // 使用 admin_id 或 user_id
            } else {
                this.selectedRows = [];
            }
        },
        deleteSelected() {
            if (this.selectedRows.length > 0) {
                this.showConfirmationDialog = true; // 显示确认对话框
            }
        },
        confirmDelete() {
            const endpoint = this.selectedTable === 'user_info' ? 'http://localhost:3000/api/users' : 'http://localhost:3000/api/admins';
            fetch(endpoint, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    ids: this.selectedRows, // 选中的用户或管理员 ID 数组
                }),
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(errorData => {
                        console.error('删除响应内容:', errorData);
                        throw new Error(`删除失败: ${response.status} ${response.statusText}`);
                    });
                }
                return response.json();
            })
            .then(result => {
                this.data = this.data.filter(item => !this.selectedRows.includes(item.admin_id || item.user_id)); // 更新前端数据
                this.selectedRows = []; // 清空选中的行
                this.showConfirmationDialog = false; // 关闭对话框
                alert(result.message); // 显示成功消息
            })
            .catch(error => {
                console.error('删除失败:', error);
                alert('删除失败，请重试！');
            });
        },
        cancelDelete() {
            this.showConfirmationDialog = false; // 关闭对话框
        },
        prevPage() {
            if (this.currentPage > 1) {
                this.currentPage--;
            }
        },
        nextPage() {
            if (this.currentPage < this.totalPages) {
                this.currentPage++;
            }
        },
        startEdit(item, field) {
            if (field !== 'nickname' && field !== 'company' && field !== 'department' && field !== 'position' && field !== 'email' && field !== 'phone') {
                return; // 不允许编辑 ID 字段
            }
            this.editingItem = item; // 设置当前编辑的项
            this.editingField = field; // 设置当前编辑的字段
            this.newValue = item[field]; // 获取当前字段的值
        },
        saveEdit() {
            if (this.editingItem && this.editingField) {
                this.editingItem[this.editingField] = this.newValue; // 更新数据
                const endpoint = this.selectedTable === 'user_info' ? 'http://localhost:3000/api/old/user_info' : 'http://localhost:3000/api/old/admin_info';
                fetch(`${endpoint}/${this.editingItem.admin_id || this.editingItem.user_id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ [this.editingField]: this.newValue }), // 发送更新的字段和新值
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('更新失败');
                    }
                    this.editingItem = null; // 清空编辑项
                    this.editingField = null; // 清空编辑字段
                })
                .catch(error => {
                    console.error('更新失败:', error);
                });
            }
        },
    },
    mounted() {
        this.fetchData(); // 组件挂载时获取数据
    },
};
</script>

<style scoped>
.container {
    display: flex;
    flex-direction: column;
    height: 950px;
    margin-bottom: 120px;
    background-color: white; /* 白色背景 */
    border-radius: 10px; /* 圆角 */
    padding: 10px; /* 内边距 */
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 添加阴影 */
}

.header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.select-table {
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    height: 34px;
    margin-right: 10px;
}

.search-filters {
    display: flex;
    gap: 10px;
}

.search-filters input {
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    height: 34px;
    flex: 1;
    transition: border-color 0.3s;
}

.search-filters input:hover {
    border-color: #007bff;
}

.search-button {
    padding: 8px 16px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    height: 34px;
    margin-right: 3px; /* 添加3px的间隔 */
}

.search-button:hover {
    background-color: #0056b3;
}

.delete-button {
    padding: 8px 16px;
    background-color: #dc3545;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    height: 34px;
    margin-left: 3px; /* 添加3px的间隔 */
}

.delete-button:hover {
    background-color: #a71d2a;
}

.data-table {
    width: 100%;
    border-collapse: collapse;
}

.data-table th, .data-table td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
}

.data-table th {
    background-color: #f2f2f2;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.pagination-button {
    padding: 8px 16px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    height: 34px;
    margin: 0 5px;
}

.pagination-button:hover {
    background-color: #0056b3;
}

.pagination-button:disabled {
    background-color: #ccc;
    cursor: not-allowed;
}
</style>